package org.redmagic.location.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.redmagic.api.HttpConnection;

public class SimpleHttpConnection implements HttpConnection {

    public String call(String urlString) {
        URL url = createUrl(urlString);
        return connect(url);
    }

    private URL createUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            return url;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private String connect(URL url) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String result = null;
        try {
            result = retrieveResult(url);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        } finally {
            close(reader, connection);
        }
        return result;
    }

    private String retrieveResult(URL url) throws IOException, ProtocolException {
        HttpURLConnection connection = setUpConnection(url);
        BufferedReader reader = setUpReader(connection);
        String result = readContents(reader);
        checkStatusCode(connection);
        return result;
    }

    private HttpURLConnection setUpConnection(URL url) throws IOException, ProtocolException {
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(500);
        connection.connect();
        return connection;
    }

    private BufferedReader setUpReader(HttpURLConnection connection) throws IOException {
        return new BufferedReader(new InputStreamReader(connection.getInputStream()));
    }
    

    private String readContents(BufferedReader reader) throws IOException {
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
    

    private void checkStatusCode(HttpURLConnection connection) throws IOException {
        int responseCode = connection.getResponseCode();
        if (responseCode > 299) {
            throw new RuntimeException("Received a response code of: " + responseCode);
        }
    }

    private void close(BufferedReader reader, HttpURLConnection connection) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
}